package com.koron.ticket.work.workticket.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.post.query.PostUserQuery;
import com.koron.bean.system.post.vo.PostUserVo;
import com.koron.bean.system.staff.StaffBean;
import com.koron.bean.system.staff.vo.AppUserVo;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.workflow.SubmitterParam;
import com.koron.bean.workflow.WorkflowUser;
import com.koron.common.core.business.system.feign.SystemFeignService;
import com.koron.common.core.business.workflow.templates.WorkFlowHandler;
import com.koron.common.core.business.workflow.util.TextUtil;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CommonUtils;
import com.koron.common.core.util.FastJsonUtils;
import com.koron.common.core.util.StringUtils;
import com.koron.ticket.work.common.bean.FifteenTables;
import com.koron.ticket.work.common.bean.FourteenTables;
import com.koron.ticket.work.common.bean.SixteenTables;
import com.koron.ticket.work.enums.TicketStatus;
import com.koron.ticket.work.enums.TicketType;
import com.koron.ticket.work.logicticket.electricalfirst.service.ElectricalFirstService;
import com.koron.ticket.work.logicticket.electricalsecond.service.ElectricalSecondService;
import com.koron.ticket.work.logicticket.firstlevelhotwork.service.FirstLevelHotWorkService;
import com.koron.ticket.work.logicticket.hightask.HighTaskService;
import com.koron.ticket.work.logicticket.hightask.bean.HighTaskDto;
import com.koron.ticket.work.logicticket.mechanicalticket.service.MechanicalTicketService;
import com.koron.ticket.work.logicticket.powerlinefirst.service.PowerLineFirstService;
import com.koron.ticket.work.logicticket.powerlinesecond.service.PowerLineSecondservice;
import com.koron.ticket.work.logicticket.secondlevelhotwork.service.SecondLevelHotWorkService;
import com.koron.ticket.work.logicticket.thirdticket.service.ThirdTicketService;
import com.koron.ticket.work.logicticket.ychoistingsafety.HoistingService;
import com.koron.ticket.work.logicticket.ychoistingsafety.bean.HoistingDto;
import com.koron.ticket.work.logicticket.ychotsafework.HotWorkSafeService;
import com.koron.ticket.work.logicticket.ychotsafework.bean.HotWorkSafeDto;
import com.koron.ticket.work.logicticket.ycpowerlinefirst.YcLineFirstService;
import com.koron.ticket.work.logicticket.ycpowerlinefirst.bean.YcLineFirstDto;
import com.koron.ticket.work.logicticket.ycpowerlinesecond.YcLineSecondService;
import com.koron.ticket.work.logicticket.ycpowerlinesecond.bean.YcLineSecondDto;
import com.koron.ticket.work.logicticket.yctempusepower.TempUserPowerService;
import com.koron.ticket.work.logicticket.yctempusepower.bean.TempUserPowerDto;
import com.koron.ticket.work.securityarrangement.bean.SecurityArrangement;
import com.koron.ticket.work.securityarrangement.bean.SecurityArrangementQuery;
import com.koron.ticket.work.securityarrangement.service.SecurityArrangementService;
import com.koron.ticket.work.workend.bean.WorkEnd;
import com.koron.ticket.work.workend.bean.WorkEndQuery;
import com.koron.ticket.work.workend.service.WorkEndService;
import com.koron.ticket.work.workflow.bean.WorkFlow;
import com.koron.ticket.work.workflow.bean.WorkFlowQuery;
import com.koron.ticket.work.workflow.service.WorkFlowService;
import com.koron.ticket.work.workinfo.bean.WorkInfo;
import com.koron.ticket.work.workinfo.bean.WorkInfoQuery;
import com.koron.ticket.work.workinfo.service.WorkInfoService;
import com.koron.ticket.work.worklocation.bean.WorkLocationBean;
import com.koron.ticket.work.worklocation.mapper.WorkLocationMapper;
import com.koron.ticket.work.workteam.service.WorkTeamService;
import com.koron.ticket.work.workticket.bean.WorkTicket;
import com.koron.ticket.work.workticket.bean.WorkTicketQuery;
import com.koron.ticket.work.workticket.mapper.WorkTicketMapper;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WorkTicketService {

    private EamUser getEamUser() {
        return ThreadLocalContext.get();
    }

    @Autowired
    private ElectricalFirstService electricalFirstService;

    @Autowired
    private ElectricalSecondService electricalSecondService;

    @Autowired
    private ThirdTicketService thirdTicketService;

    @Autowired
    private MechanicalTicketService mechanicalTicketService;

    @Autowired
    private PowerLineFirstService powerLineFirstService;

    @Autowired
    private PowerLineSecondservice powerLineSecondservice;

    @Autowired
    private HighTaskService hightaskservice;

    @Autowired
    private HotWorkSafeService hotworksafeservice;

    @Autowired
    private TempUserPowerService tempuserpowerservice;

    @Autowired
    private HoistingService hoistingservice;

    @Autowired
    private YcLineFirstService yclinefirstservice;

    @Autowired
    private YcLineSecondService yclinesecondservice;

    @Autowired
    private FirstLevelHotWorkService firstLevelHotWorkService;

    @Autowired
    private SecondLevelHotWorkService secondLevelHotWorkService;

    @Autowired
    private WorkTeamService workTeamService;

    @Autowired
    private SecurityArrangementService securityArrangementService;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private WorkEndService workEndService;

    @Autowired
    private WorkInfoService workInfoService;

    @Autowired
    private SystemFeignService systemfeignservice;//获取审批人 公共接口

    @Autowired
    private WorkFlowHandler workFlowHandler;

    // 前端流程提交检查
    @TaskAnnotation("checkTimeOutforeend")
    public void checkTimeOutforeend(SessionFactory factory, String ticketId, Date updateTime) {
        checkTimeOnTCommon(factory, ticketId, updateTime);
    }

    // 保存检查并更新最后更新时间
    public void checkTimeOut(SessionFactory factory, String ticketId, Date updateTime) {
        WorkTicketMapper mapper = factory.getMapper(WorkTicketMapper.class);
        checkTimeOnTCommon(factory, ticketId, updateTime);
        mapper.updateUpdateTimeAndUpdateUserIdAndUpdateUserNameById(new Date(), getEamUser().getAccount(), getEamUser().getName(), ticketId);
    }

    // 公共检查
    private void checkTimeOnTCommon(SessionFactory factory, String ticketId, Date updateTime) {
        if (StrUtil.isBlank(ticketId)) {
            return;
        }
        WorkTicketMapper mapper = factory.getMapper(WorkTicketMapper.class);
        WorkTicket single = mapper.getSingle(new WorkTicketQuery(ticketId));
        if (single.getUpdateTime() == null || updateTime == null) {
            return;
        }
        //是否小于数据库最后更新时间
        long between = DateUtil.between(single.getUpdateTime(), updateTime, DateUnit.MS, false);
        if (between < 0) {
            Assert.isFalse(true, "信息已过期请刷新界面");
            return;
        }
        return;
    }


    @TaskAnnotation("addWorkTicket")
    public Response addWorkTicket(SessionFactory factory, String type) {
        if (type.equals(TicketType.ElectricalFirst.getType())) {
            // 1. 电气第一种工作票
            FifteenTables fifteenTables = electricalFirstService.add();
            return Response.success(fifteenTables);
        } else if (type.equals(TicketType.ElectricalSecond.getType())) {
            // 2. 电气第二种工作票
            FifteenTables fifteenTables = electricalSecondService.add();
            return Response.success(fifteenTables);
        } else if (type.equals(TicketType.ThirdTicket.getType())) {
            // 3. 第三种工作票
            FourteenTables fourteenTables = thirdTicketService.add();
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.MechanicalTicket.getType())) {
            // 4. 机械工作票
            FourteenTables fourteenTables = mechanicalTicketService.add();
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.PowerLineFirst.getType())) {
            // 5. 电力线路第一种工作票
            SixteenTables sixteenTables = powerLineFirstService.add();
            return Response.success(sixteenTables);
        } else if (type.equals(TicketType.PowerLineSecond.getType())) {
            // 6. 电力线路第二种工作票
            SixteenTables sixteenTables = powerLineSecondservice.add();
            return Response.success(sixteenTables);
        } else if (type.equals(TicketType.FirstLevelHotWork.getType())) {
            // 7. 一级动火工作票
            FourteenTables fourteenTables = firstLevelHotWorkService.add();
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.SecondLevelHotWork.getType())) {
            // 8. 二级动火工作票
            FourteenTables fourteenTables = secondLevelHotWorkService.add();
            return Response.success(fourteenTables);
        } else {
            return Response.fail("没有这种工作票");
        }
    }

    @TaskAnnotation("getListAndPaging")
    public Response getListAndPaging(SessionFactory factory, WorkTicketQuery workTicketQuery) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);

        // 1. 根据条件分页查询
        List<WorkTicket> workTicketList = workTicketMapper.getListAndPaging(workTicketQuery);
//        Integer total = workTicketMapper.count(workTicketQuery);
        return Response.success("查询成功", new PageInfo(workTicketList));
    }

    @TaskAnnotation("getListForChangeShifts")
    public List<WorkTicket> getListForChangeShifts(SessionFactory factory, WorkTicketQuery workTicketQuery) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);
        // 1. 根据请求查出对应的数据
        List<WorkTicket> workTicketList = workTicketMapper.getListForChangeShifts(workTicketQuery);
        for (WorkTicket workTicket : workTicketList) {
            Integer status = workTicket.getStatus();
            String workTicketId = workTicket.getId();
            // 2. 针对已归档的数据，添加实际完成时间
            if (status.equals(TicketStatus.ARCHIVED.getStatus())) {
                // 2.1 根据workTicketId查出对应的工作终结信息
                WorkEndQuery workEndQuery = new WorkEndQuery();
                workEndQuery.setWorkTicketId(workTicketId);
                List<WorkEnd> workEndList = workEndService.getList(factory, workEndQuery);
                if (workEndList.size() == 2) {
                    // 2.2 电气第一种工作票，电气第二种工作票，机械工作票，电力线路第一种工作票，电力线路第二种工作票；有两条工作终结信息，取
                    // 工作票待终结的时间
                    for (WorkEnd workEnd : workEndList) {
                        if (workEnd.getStatus() == TicketStatus.TICKET_END.getStatus()) {
                            workTicket.setRealEndTIme(workEnd.getEndTime());
                        }
                    }
                } else if (workEndList.size() == 1) {
                    // 2.3 第三种工作票，一级动火工作票，二级动火工作票；仅一条工作中介信息，可以直接使用
                    workTicket.setRealEndTIme(workEndList.get(0).getEndTime());
                }
            }
        }

        return workTicketList;
    }

    @TaskAnnotation("historyImport")
    public Response historyImport(SessionFactory factory, String id) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);

        // 1. 查出历史工作票
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(id);
        WorkTicket workTicket = workTicketMapper.getSingle(workTicketQuery);
        // 2. 查出对应的安全措施项
        String type = workTicket.getType();
        // 2.1 电气第一/二种工作票，电力线路第一种工作票的安全措施来自于SecurityArrangement
        if (type.equals(TicketType.ElectricalFirst.getType()) || type.equals(TicketType.ElectricalSecond.getType())
                || type.equals(TicketType.PowerLineFirst.getType()) || type.equals(TicketType.ZsjBidSectionFirst.getType())) {
            SecurityArrangementQuery securityArrangementQuery = new SecurityArrangementQuery();
            securityArrangementQuery.setWorkTicketId(id);
            List<SecurityArrangement> securityArrangementList = securityArrangementService.getList(factory, securityArrangementQuery);
            workTicket.setSecurityArrangementList(securityArrangementList);
        } // 2.2 其他的工作票，安全措施来自于WorkInfo
        else {
            WorkInfoQuery workInfoQuery = new WorkInfoQuery();
            workInfoQuery.setWorkTicketId(id);
            WorkInfo workInfo = workInfoService.getSingle(factory, workInfoQuery);
            workTicket.setWorkInfo(workInfo);
        }

        return Response.success(workTicket);
    }

    @TaskAnnotation("getByIdAndType")
    public Response getByIdAndType(SessionFactory factory, String id, String type) {
        // 1. 根据工作票类型返回不同的数据
        if (StringUtils.equalsAny(type, TicketType.ElectricalFirst.getType(), TicketType.ZsjBidSectionFirst.getType(), TicketType.ZsjBidSectionSecond.getType())) {
            FifteenTables fifteenTables = electricalFirstService.getById(factory, id);
            return Response.success(fifteenTables);
        } else if (type.equals(TicketType.ElectricalSecond.getType())) {
            FifteenTables fifteenTables = electricalSecondService.getById(factory, id);
            return Response.success(fifteenTables);
        } else if (type.equals(TicketType.ThirdTicket.getType())) {
            FourteenTables fourteenTables = thirdTicketService.getById(factory, id);
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.MechanicalTicket.getType())) {
            FourteenTables fourteenTables = mechanicalTicketService.getById(factory, id);
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.FirstLevelHotWork.getType())) {
            FourteenTables fourteenTables = firstLevelHotWorkService.getById(factory, id);
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.SecondLevelHotWork.getType())) {
            FourteenTables fourteenTables = firstLevelHotWorkService.getById(factory, id);
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.PowerLineFirst.getType())) {
            SixteenTables sixteenTables = powerLineFirstService.getById(factory, id);
            return Response.success(sixteenTables);
        } else if (type.equals(TicketType.PowerLineSecond.getType())) {
            FourteenTables fourteenTables = powerLineSecondservice.getById(factory, id);
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.HighTaskTicket.getType())) {
            HighTaskDto dto = hightaskservice.getById(factory, id);
            return Response.success(dto);
        } else if (type.equals(TicketType.HotSafetyTicket.getType())) {
            HotWorkSafeDto dto = hotworksafeservice.getById(factory, id);
            return Response.success(dto);
        } else if (type.equals(TicketType.TempUsePowerSecure.getType())) {
            TempUserPowerDto dto = tempuserpowerservice.getById(factory, id);
            return Response.success(dto);
        } else if (type.equals(TicketType.HoistingSafety.getType())) {
            HoistingDto dto = hoistingservice.getById(factory, id);
            return Response.success(dto);
        } else if (type.equals(TicketType.YcPowerLineFirst.getType())) {
            YcLineFirstDto dto = yclinefirstservice.getById(factory, id);
            return Response.success(dto);
        } else if (type.equals(TicketType.YcPowerLineSecond.getType())) {
            YcLineSecondDto dto = yclinesecondservice.getById(factory, id);
            return Response.success(dto);
        } else {
            return Response.fail("查找失败");
        }
    }

    @TaskAnnotation("getById")
    public Response getById(SessionFactory factory, String id) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(id);
        WorkTicket workTicket = workTicketMapper.getSingle(workTicketQuery);
        String type = workTicket.getType();

        // 1. 根据工作票类型返回不同的数据
        if (StringUtils.equalsAny(type, TicketType.ElectricalFirst.getType(), TicketType.ZsjBidSectionFirst.getType(), TicketType.ZsjBidSectionSecond.getType())) {
            FifteenTables fifteenTables = electricalFirstService.getById(factory, id);
            return Response.success(fifteenTables);
        } else if (type.equals(TicketType.ElectricalSecond.getType())) {
            FifteenTables fifteenTables = electricalSecondService.getById(factory, id);
            return Response.success(fifteenTables);
        } else if (type.equals(TicketType.ThirdTicket.getType())) {
            FourteenTables fourteenTables = thirdTicketService.getById(factory, id);
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.MechanicalTicket.getType())) {
            FourteenTables fourteenTables = mechanicalTicketService.getById(factory, id);
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.FirstLevelHotWork.getType())) {
            FourteenTables fourteenTables = firstLevelHotWorkService.getById(factory, id);
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.SecondLevelHotWork.getType())) {
            FourteenTables fourteenTables = firstLevelHotWorkService.getById(factory, id);
            return Response.success(fourteenTables);
        } else if (type.equals(TicketType.PowerLineFirst.getType())) {
            FourteenTables fourteenTables = powerLineFirstService.getById(factory, id);
            return Response.success(fourteenTables);
        }else if (type.equals(TicketType.PowerLineSecond.getType())) {
            FourteenTables fourteenTables = powerLineSecondservice.getById(factory, id);
            return Response.success(fourteenTables);
        } else {
            return Response.fail("查找失败");
        }
    }

    @TaskAnnotation("deleteByIdAndType")
    public Response deleteByIdAndType(SessionFactory factory, String id, String type, Date updateTime) {
        checkTimeOut(factory, id, updateTime);//检查信息是否过期
        this.deleteById(factory, id);
        //删除工作流记录
        boolean delete = workFlowHandler.delete(id);
        Assert.isTrue(delete, "工作流删除异常");
        return Response.success("删除成功");
    }

    @TaskAnnotation("electronicSignatureCallback")
    public Response electronicSignatureCallback(SessionFactory factory, String workTicketId, String tenantName, String signStatus) {
        WorkFlowQuery workFlowQuery = new WorkFlowQuery();
        workFlowQuery.setWorkTicketId(workTicketId);
        List<WorkFlow> workFlowList = workFlowService.getList(factory, workFlowQuery);
        for (WorkFlow workFlow : workFlowList) {
            Integer deleteFlag = workFlow.getDeleteFlag();
            String name = workFlow.getName();
            // 20211116: deleteFlag的含义：0：已签名 1：电子签-保存 2：电子签-已要求签名（用户未签名），用于限制签名次数
            if (deleteFlag == 2 && name.equals(tenantName)) {
                // 更新签名状态
                workFlow.setDeleteFlag(0);
                workFlowService.update(factory, workFlow);
                WorkTicketQuery workTicketQuery = new WorkTicketQuery();
//                // 更新工作票预览状态
//                workTicketQuery.setId(workTicketId);
//                WorkTicket workTicket = this.getSingle(factory,workTicketQuery);
//                workTicket.setPreviewFlag(1);
//                this.update(factory,workTicket);
            }
        }

        return Response.success("工作票-电子签章，回调成功");
    }

    public void insert(SessionFactory factory, WorkTicket workTicket) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);
        workTicket.setCreateTime(new Date());
        workTicket.setUpdateTime(new Date());
        workTicket.setCreateUserName(getEamUser().getName());
        workTicket.setCreateDept(getEamUser().getOrgId());
        workTicket.setCreateDeptName(getEamUser().getOrgName());
        workTicketMapper.insert(workTicket);
    }

    public WorkTicket getSingle(SessionFactory factory, WorkTicketQuery workTicketQuery) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);
        WorkTicket workTicket = workTicketMapper.getSingle(workTicketQuery);
        return workTicket;
    }

    public WorkTicket queryById(SessionFactory factory, String id) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);
        WorkTicket workTicket = workTicketMapper.queryById(id);
        return workTicket;
    }

    public void deleteById(SessionFactory factory, String id) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);
//        workTicketMapper.deleteById(id);
        workTicketMapper.updateDeleteFlagById(id);
        workTicketMapper.updateUpdateTimeAndUpdateUserIdAndUpdateUserNameById(new Date(), getEamUser().getAccount(), getEamUser().getName(), id);
    }

    public String getLastCodeByUnitAndType(SessionFactory factory, String unit, String type) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);
        String code = workTicketMapper.getLastCodeByUnit(unit, type);
        return code;
    }

    public String getTypeById(SessionFactory factory, String workTicketId) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(workTicketId);
        WorkTicket workTicket = workTicketMapper.getSingle(workTicketQuery);
        return workTicket.getType();
    }

    @TaskAnnotation("update")
    public Response update(SessionFactory factory, WorkTicket workTicket) {
        WorkTicketMapper workTicketMapper = factory.getMapper(WorkTicketMapper.class);
        workTicket.setUpdateTime(new Date());
        workTicket.setUpdateUserId(getEamUser().getAccount());
        workTicket.setUpdateUserName(getEamUser().getName());
        workTicketMapper.update(workTicket);

        return Response.success("更新成功");
    }

    /**
     * @param submitterParam 请求参数
     * @param orgName        部门名字
     * @param type           1、本单位带岗位和条件  2、本部门带岗位和条件  3、岗位和条件  4、只有本单位的任何人
     *                       注意：单位和部门是有区别的
     * @return
     */
    public List<WorkflowUser> getWorkflowUsers(SubmitterParam submitterParam, String orgName, Integer type) {
        String currDs = ThreadLocalContext.get().getCurrDs();
        log.info("接收到的参数:" + FastJsonUtils.getBeanToJson(submitterParam));
        Map<String, String> infoMap = TextUtil.toMapFromString(submitterParam.getFormVariables());
        // 开票单位
        String unit = infoMap.get("unit");
        if (CollUtil.isNotEmpty(submitterParam.getUsers())) {
            List<String> deptIds = submitterParam.getUsers().stream().filter(f -> f.getType() == 1).map(WorkflowUser::getCode).collect(Collectors.toList());
            if (deptIds.contains(unit)) {
                return null;
            }
        }
        PostUserQuery postUserQuery = new PostUserQuery();
        if (StringUtils.isNotEmpty(submitterParam.getUsers())) {
            postUserQuery.setPostIdList(submitterParam.getUsers().stream().filter(sub -> sub.getType() == 2).map(WorkflowUser::getCode).collect(Collectors.toList()));//岗位id赋值
        }
        if (StrUtil.isNotBlank(orgName)) {
            postUserQuery.setOrgNameList(CollUtil.newArrayList(orgName));      //部门名字
        }
        List<WorkflowUser> list = new ArrayList<>();

        if (type == 1) {
            list = ADOConnection.runTask(currDs, this, "getTicketApproverThisUnit", List.class, infoMap.get("id"), postUserQuery);//只查询本单位 和 带的条件
        }
        if (type == 2) {
            list = ADOConnection.runTask(currDs, this, "getTicketApproverThisDeptBg", List.class, infoMap.get("id"), postUserQuery);//只查询本部门 和 带的条件
        }
        if (type == 3) {
            if (StringUtils.isNotEmpty(submitterParam.getUsers())) {
                postUserQuery.setOrgIdList(submitterParam.getUsers().stream().filter(sub -> sub.getType() == 1).map(WorkflowUser::getCode).collect(Collectors.toList()));//组织id赋值
            }
            list = getWorkflowUsers(postUserQuery);//只有页面配置的条件
        }
        if (type == 4) {
            list = ADOConnection.runTask(currDs, this, "getTicketApproverThisUnitNoPost", List.class, infoMap.get("id"));//只查询本单位
        }
        // 20220325 刘子扬-所有票所有节点 开票单位下的人都可以审核
//        list.addAll(ADOConnection.runTask(currDs, this, "getTicketApproverThisUnitNoPost", List.class, infoMap.get("id")));//只查询本单位
        log.info("返回到的人员:" + FastJsonUtils.getBeanToJson(list));
        return list;
    }

    /**
     * 获取审批人
     * 查出本单位的集合
     *
     * @param id 工作票id
     * @return
     */
    @TaskAnnotation("getTicketApproverThisUnitNoPost")
    public List<WorkflowUser> getTicketApproverThisUnitNoPost(SessionFactory factory, String id) {
        String unit = factory.getMapper(WorkTicketMapper.class).getSingle(new WorkTicketQuery(id)).getUnit();//获取开票单位id
        StaffBean staffBean = new StaffBean();
        staffBean.setOrgId(unit);
        List<WorkflowUser> resultlist = getWorkflowThisUnitUsers(staffBean);
        if (StringUtils.isNotEmpty(resultlist)) {
            return resultlist;
        }
        return new ArrayList();
    }

    /**
     * 获取审批人
     * 查出本部门人员集合
     *
     * @param id 工作票id
     * @return
     */
    @TaskAnnotation("getTicketApproverThisOrgNoPost")
    public List<WorkflowUser> getTicketApproverThisOrgNoPost(SessionFactory factory, String id) {
        // 找出创建票单位
        String createDept = factory.getMapper(WorkTicketMapper.class).getSingle(new WorkTicketQuery(id)).getCreateDept();//获取开票单位id

        // 远程调用找部门id
        Response<OrgBean> orgBeanResponse = systemfeignservice.queryDeptByOrgId(createDept);
        OrgBean ok = CommonUtils.ok(orgBeanResponse);
        String orgId = ok.getId();

        // 远程调用找出部门id
        StaffBean staffBean = new StaffBean();
        staffBean.setOrgId(orgId);
        List<WorkflowUser> resultlist = getWorkflowThisUnitUsers(staffBean);
        if (StringUtils.isNotEmpty(resultlist)) {
            return resultlist;
        }
        return new ArrayList();
    }


    /**
     * 获取审批人
     * 查出本单位带岗位人员的集合
     *
     * @param id 工作票id
     * @return
     */
    @TaskAnnotation("getTicketApproverThisUnit")
    public List<WorkflowUser> getTicketApproverThisUnit(SessionFactory factory, String id, PostUserQuery postUserQuery) {
        String unit = factory.getMapper(WorkTicketMapper.class).getSingle(new WorkTicketQuery(id)).getUnit();//获取开票单位id
        postUserQuery.setOrgIdList(CollUtil.newArrayList(unit));
        List<WorkflowUser> resultlist = getWorkflowUsers(postUserQuery);
        if (StringUtils.isNotEmpty(resultlist)) {
            return resultlist;
        }
        return new ArrayList();
    }

    /**
     * 获取审批人
     * 查出相应部门 和 条件人员的集合
     *
     * @param id 工作票id
     * @return
     */
    @TaskAnnotation("getTicketApproverThisDeptBg")
    public List<WorkflowUser> getTicketApproverThisDeptBg(SessionFactory factory, String id, PostUserQuery postUserQuery) {
        //填写、待许可
        String unit = factory.getMapper(WorkTicketMapper.class).getSingle(new WorkTicketQuery(id)).getUnit();//获取开票单位id
        Response<OrgBean> response = systemfeignservice.queryDeptByOrgId(unit);//获取部门id
        Assert.isFalse(response.getCode() != 200, response.getDescription());
        String orgId = "";//部门id
        if (response.getCode() == 200) {
            OrgBean resultdata = response.getData();
            orgId = resultdata.getId();
        }
        postUserQuery.setParentOrgIdList(CollUtil.newArrayList(orgId));
        List<WorkflowUser> resultlist = getWorkflowUsers(postUserQuery);
        if (StringUtils.isNotEmpty(resultlist)) {
            return resultlist;
        }
        return new ArrayList();
    }


    /**
     * 调公共接口查审批人员
     * 查出的人员 都有岗位的
     *
     * @param postUserQuery
     * @return
     */
    public List<WorkflowUser> getWorkflowUsers(PostUserQuery postUserQuery) {
        Response<List<PostUserVo>> listResponse = systemfeignservice.queryPostList(postUserQuery);//查出符合条件的审批人
        Assert.isFalse(listResponse.getCode() != 200, listResponse.getDescription());
        if (listResponse.getCode() == 200) {
            List<PostUserVo> ulist = listResponse.getData();
            if (StringUtils.isEmpty(ulist)) {
                return new ArrayList();
            }
            List<WorkflowUser> resultlist = ulist.stream().map(vo -> {
                WorkflowUser workflowuser = new WorkflowUser();
                workflowuser.setCode(vo.getUserAccount());
                workflowuser.setName(vo.getUserName());
                return workflowuser;
            }).collect(Collectors.toList());
            return resultlist;
        }
        return null;
    }

    /**
     * 调公共接口查审批人员
     *
     * @param staffbean
     * @return
     */
    public List<WorkflowUser> getWorkflowThisUnitUsers(StaffBean staffbean) {
        Response<List<AppUserVo>> listResponse = systemfeignservice.queryStaffListByOrgWithMerge(staffbean, 0, 1);//查出符合条件的审批人
        Assert.isFalse(listResponse.getCode() != 200, listResponse.getDescription());
        if (listResponse.getCode() == 200) {
            List<AppUserVo> ulist = listResponse.getData();
            if (StringUtils.isEmpty(ulist)) {
                return new ArrayList();
            }
            List<WorkflowUser> resultlist = ulist.stream().map(vo -> {
                WorkflowUser workflowuser = new WorkflowUser();
                workflowuser.setCode(vo.getAccount());
                workflowuser.setName(vo.getName());
                return workflowuser;
            }).collect(Collectors.toList());
            return resultlist;
        }
        return null;
    }


    public void updatePreviewFlagById(SessionFactory factory, String id) {
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(id);
        WorkTicket workTicket = this.getSingle(factory, workTicketQuery);
        workTicket.setPreviewFlag(1);
        this.update(factory, workTicket);
    }

    /**
     * 获取工作地点
     *
     * @param factory
     * @param ticketIds
     * @return
     */
    public Map<String, List<WorkLocationBean>> getLoctionByTicket(SessionFactory factory, List<String> ticketIds) {
        if (CollUtil.isNotEmpty(ticketIds)) {
            return null;
        }
        List<WorkLocationBean> loctionlist = factory.getMapper(WorkLocationMapper.class).queryByWorkTicketIdIn(ticketIds);
        Map<String, List<WorkLocationBean>> map = loctionlist.stream().collect(Collectors.groupingBy(WorkLocationBean::getWorkTicketId));
        return map;
    }

    /**
     * 更新最后更新时间
     *
     * @param factory
     * @param ticketId
     */
    @TaskAnnotation("updateUpdateTime")
    public void updateUpdateTime(SessionFactory factory, String ticketId) {
        WorkTicketMapper mapper = factory.getMapper(WorkTicketMapper.class);
        mapper.updateUpdateTimeAndUpdateUserIdAndUpdateUserNameById(new Date(), getEamUser().getAccount(), getEamUser().getName(), ticketId);
    }
}
